﻿using AutoMapper;
using JTTD.Common.Helper;
using JTTD.DataBase;
using JTTD.DataBase.Model.Activity;
using JTTD.Domain.Dtos;
using JTTD.Domain.Dtos.Activity.Response;
using JTTD.Domain.Dtos.Activity.Request;
using JTTD.Domain.IService;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace JTTD.Domain.Service
{
    /// <summary>
    /// 商城活动服务
    /// </summary>
    public class ActivityService : IActivityService
    {
        private readonly JTTDContext _dbContext;
        private readonly IMapper _mapper;
        private readonly IIntegralService _integralService;
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="mapper"></param>
        public ActivityService(JTTDContext context, IMapper mapper, IIntegralService integralService)
        {
            _dbContext = context;
            _mapper = mapper;
            _integralService = integralService;
        }

        /// <summary>
        /// 更改商城活动启用状态
        /// </summary>
        /// <param name="activityId"></param>
        /// <param name="isEnable"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> ChangeEnable(int activityId, bool isEnable)
        {
            try
            {
                var model = await _dbContext.ActivityInfoModels.FindAsync(activityId);
                if (model == null)
                {
                    throw new Exception("没有找到指定条件的商城活动");
                }
                if (model.Type == Common.Enum.ActivityTypeEnum.MultipleIntegral)
                {
                    //倍数积分活动同一时间段只能允许一个活动生效
                    var exists = await _dbContext.ActivityInfoModels.FirstOrDefaultAsync(item => item.Type == model.Type && item.IsEnable);
                    if (exists != null)
                    {
                        throw new Exception($"已存在其他{exists.Type.GetDescription()}：{exists.No}处于启用中");
                    }
                }
                model.IsEnable = isEnable;
                _dbContext.ActivityInfoModels.Update(model);
                await _dbContext.SaveChangesAsync();
                return new ApiResult<bool>() { IsSuccess = true, Message = "操作成功" };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>() { IsSuccess = false, Message = "操作失败，" + ex.Message };
            }
        }

        /// <summary>
        /// 删除商城活动
        /// </summary>
        /// <param name="activityId"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> DeleteActivity(int activityId)
        {
            try
            {
                var model = await _dbContext.ActivityInfoModels.FindAsync(activityId);
                if (model == null)
                {
                    throw new Exception("没有找到指定条件的商城活动");
                }
                model.IsDelete = true;
                _dbContext.ActivityInfoModels.Update(model);
                await _dbContext.SaveChangesAsync();
                return new ApiResult<bool>() { IsSuccess = true, Message = "操作成功" };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>() { IsSuccess = false, Message = "操作失败，" + ex.Message };
            }
        }

        /// <summary>
        /// 获取单个商城活动
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResult<ActivityInfoResponseDto>> GetActivity(int id)
        {
            try
            {
                var model = await _dbContext.ActivityInfoModels.FindAsync(id);
                if (model == null)
                {
                    throw new Exception("没有找到指定条件的商城活动");
                }
                return new ApiResult<ActivityInfoResponseDto>() { IsSuccess = true, Data = _mapper.Map<ActivityInfoResponseDto>(model) };
            }
            catch (Exception ex)
            {
                return new ApiResult<ActivityInfoResponseDto>() { Message = "查询失败，" + ex.Message, Data = new ActivityInfoResponseDto(), IsSuccess = false };
            }
        }

        /// <summary>
        /// 分页获取商城活动
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult<PageResult<ActivityInfoResponseDto>>> GetActivityPageList(SearchActivityRequestDto dto)
        {
            try
            {
                var query = _dbContext.ActivityInfoModels.Where(item => !item.IsDelete);
                if (dto.IsEnable.HasValue)
                {
                    query = query.Where(item => item.IsEnable == dto.IsEnable.Value);
                }
                if (!string.IsNullOrWhiteSpace(dto.No))
                {
                    query = query.Where(item => item.No == dto.No.Trim());
                }
                int count = await query.CountAsync();
                if (count > 0)
                {
                    var list = await query.OrderByDescending(item => item.No).Skip((dto.PageIndex - 1) * dto.PageSize).Take(dto.PageSize).ToListAsync();
                    return new ApiResult<PageResult<ActivityInfoResponseDto>>()
                    {
                        Data = new PageResult<ActivityInfoResponseDto>()
                        {
                            Data = _mapper.Map<List<ActivityInfoResponseDto>>(list),
                            PageIndex = dto.PageIndex,
                            PageSize = dto.PageSize,
                            TotalNum = count,
                            TotalPageNum = (count % dto.PageSize) == 0 ? count / dto.PageSize : count / dto.PageSize + 1
                        },
                        IsSuccess = true
                    };
                }
                else
                {
                    return new ApiResult<PageResult<ActivityInfoResponseDto>>()
                    {
                        Data = new PageResult<ActivityInfoResponseDto>()
                        {
                            PageIndex = dto.PageIndex,
                            PageSize = dto.PageSize,
                            Data = new List<ActivityInfoResponseDto>()
                        },
                        IsSuccess = true,
                        Message = "查询成功，暂无数据"
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<PageResult<ActivityInfoResponseDto>>()
                {
                    IsSuccess = false,
                    Message = "查询失败，" + ex.Message
                };
            }
        }

        /// <summary>
        /// 获取所有启用中的商城活动
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<List<ActivityInfoResponseDto>>> GetEnableActivityList()
        {
            try
            {
                var list = await _dbContext.ActivityInfoModels.Where(item =>!item.IsDelete&& item.IsEnable && item.StartTime <= DateTime.Now && DateTime.Now <= item.EndTime).ToListAsync();
                if (list.Any())
                {
                    return new ApiResult<List<ActivityInfoResponseDto>>()
                    {
                        IsSuccess = true,
                        Data = _mapper.Map<List<ActivityInfoResponseDto>>(list)
                    };
                }
                else
                {
                    return new ApiResult<List<ActivityInfoResponseDto>>()
                    {
                        IsSuccess = true,
                        Message = "查询成功，暂无数据",
                        Data = new List<ActivityInfoResponseDto>()
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<List<ActivityInfoResponseDto>>()
                {
                    IsSuccess = false,
                    Message = "查询失败，" + ex.Message
                };
            }
        }

        /// <summary>
        /// 参与商城活动
        /// </summary>
        /// <param name="activityId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> JoinActivity(int activityId, int userId)
        {
            try
            {
                var activity = await _dbContext.ActivityInfoModels.FindAsync(activityId);
                if (activity == null)
                {
                    throw new Exception("没有找到指定条件的商城活动");
                }
                if (!(activity.StartTime <= DateTime.Now && DateTime.Now <= activity.EndTime) && activity.IsEnable && !activity.IsDelete)
                {
                    throw new Exception("当前商城活动已过期");
                }
                var user = await _dbContext.UserInfos.FindAsync(userId);
                if (user == null)
                {
                    throw new Exception("获取当前用户失败");
                }
                bool exists = (await _dbContext.ActivityJoinUserModels.CountAsync(item => item.ActivityId == activityId && item.UserId == userId)) > 0;
                if (exists)
                {
                    throw new Exception("您已经参加过本次活动");
                }
                _dbContext.Database.BeginTransaction();
                //更新用户积余额
                //user.Integral = user.Integral + activity.IntegralAmount;
                _dbContext.UserInfos.Update(user);
                //新增积分收支记录
                var recordModel = new DataBase.Model.Integral.IntrgralRecordModel();

                recordModel.UserId = userId;
                recordModel.Type = Common.Enum.RecordTypeEnum.Income;
                recordModel.Integral = activity.IntegralAmount;
                recordModel.OperatingTime = DateTime.Now;
                recordModel.Before = await _integralService.GetUserIntegral(userId);
                recordModel.After = recordModel.Before + recordModel.Integral;
                    
                
                _dbContext.IntrgralRecords.Add(recordModel);
                //新增活动参与用户记录
                _dbContext.ActivityJoinUserModels.Add(new ActivityJoinUserModel { UserId = userId, ActivityId = activityId });
                await _dbContext.SaveChangesAsync();
                _dbContext.Database.CommitTransaction();
                return new ApiResult<bool>()
                {
                    IsSuccess = true,
                    Message = "操作成功"
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>()
                {
                    IsSuccess = false,
                    Message = "操作失败，" + ex.Message
                };
            }
        }

        /// <summary>
        /// 设置商城活动
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> SetActivity(SetActivityRequestDto dto)
        {
            try
            {
                if (dto.StartTime > dto.EndTime)
                {
                    throw new Exception("操作失败，活动开始时间不能大于结束时间");
                }
                if (!string.IsNullOrWhiteSpace(dto.No))
                {
                    var model = await _dbContext.ActivityInfoModels.FirstOrDefaultAsync(item => item.No == dto.No);
                    if (model == null)
                    {
                        throw new Exception("操作失败，没有找到指定条件的商城活动");
                    }
                    //倍数积分活动不允许时间段重复
                    if (dto.Type == Common.Enum.ActivityTypeEnum.MultipleIntegral)
                    {
                        var exists = _dbContext.ActivityInfoModels.FirstOrDefault(item => item.No != dto.No && item.Type == dto.Type && !(item.StartTime > dto.EndTime || item.EndTime < dto.StartTime) && !item.IsDelete);
                        if (exists != null)
                        {
                            throw new Exception($"倍数积分商城活动与已存在的活动：{exists.No}存在重复的时间范围");
                        }
                    }
                    model.Name = dto.Name;
                    model.StartTime = dto.StartTime;
                    model.EndTime = dto.EndTime;
                    model.Type = dto.Type;
                    model.IntegralAmount = dto.IntegralAmount;
                    model.Multiple = dto.Multiple;
                    model.Remark = dto.Remark;
                    model.Photo = dto.Photo;
                    _dbContext.ActivityInfoModels.Update(model);
                }
                else
                {
                    if (dto.Type == Common.Enum.ActivityTypeEnum.MultipleIntegral)
                    {
                        var exists = _dbContext.ActivityInfoModels.FirstOrDefault(item => item.Type == dto.Type && !(item.StartTime > dto.EndTime || item.EndTime < dto.StartTime) && !item.IsDelete);
                        if (exists != null)
                        {
                            throw new Exception($"倍数积分商城活动与已存在的活动：{exists.No}存在重复的时间范围");
                        }
                    }
                    var model = _mapper.Map<ActivityInfoModel>(dto);
                    model.No = "No" + DateTime.Now.Ticks;
                    _dbContext.ActivityInfoModels.Add(model);
                }
                await _dbContext.SaveChangesAsync();
                return new ApiResult<bool>()
                {
                    IsSuccess = true,
                    Message = "操作成功"
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>()
                {
                    IsSuccess = false,
                    Message = "操作失败，" + ex.Message
                };
            }
        }
    }
}